from flask import Flask, render_template, request, redirect, url_for, session, flash
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import os
from datetime import datetime

# 初始化应用
app = Flask(__name__)
app.secret_key = 'your-secret-key-here'

# 配置数据库
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'database/bank.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# 导入数据模型
from models.user import User
from models.card import Card, Deposit
from models.transaction import Transaction

# 导入服务
from services.auth import login_required, admin_required
from services.bank import deposit_money, withdraw_money, transfer_money, report_loss
from services.admin import admin_dashboard_data, customer_management


# 首页路由
@app.route('/')
def index():
    if 'user_id' in session:
        if session.get('is_admin'):
            return redirect(url_for('admin_dashboard'))
        else:
            return redirect(url_for('customer_dashboard'))
    return redirect(url_for('login'))


# 登录路由
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')

        user = User.query.filter_by(customerName=username).first()

        if user and check_password_hash(user.password, password):
            session['user_id'] = user.customerID
            session['is_admin'] = user.is_admin
            flash('登录成功', 'success')
            return redirect(url_for('index'))
        else:
            flash('用户名或密码错误', 'danger')

    return render_template('auth/login.html')


# 登出路由
@app.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出', 'info')
    return redirect(url_for('login'))


# 客户仪表盘
@app.route('/customer/dashboard')
@login_required
def customer_dashboard():
    if session.get('is_admin'):
        return redirect(url_for('admin_dashboard'))

    user = User.query.get(session['user_id'])
    cards = Card.query.filter_by(customerID=user.customerID).all()

    return render_template('customer/dashboard.html', user=user, cards=cards)


# 存款操作
@app.route('/deposit', methods=['POST'])
@login_required
def deposit():
    card_id = request.form.get('card_id')
    amount = float(request.form.get('amount'))

    result = deposit_money(card_id, amount, session['user_id'])
    flash(result['message'], 'success' if result['success'] else 'danger')

    return redirect(url_for('customer_dashboard'))


# 转账操作
@app.route('/transfer', methods=['POST'])
@login_required
def transfer():
    from_card = request.form.get('from_card')
    to_card = request.form.get('to_card')
    amount = float(request.form.get('amount'))
    password = request.form.get('password')

    result = transfer_money(from_card, to_card, amount, password, session['user_id'])
    flash(result['message'], 'success' if result['success'] else 'danger')

    return redirect(url_for('customer_dashboard'))


# 管理员仪表盘
@app.route('/admin/dashboard')
@admin_required
def admin_dashboard():
    data = admin_dashboard_data()
    return render_template('admin/dashboard.html', **data)


# 客户管理
@app.route('/admin/customers', methods=['GET', 'POST'])
@admin_required
def manage_customers():
    if request.method == 'POST':
        action = request.form.get('action')
        customer_id = request.form.get('customer_id')
        result = customer_management(action, request.form, customer_id)
        flash(result['message'], 'success' if result['success'] else 'danger')

    customers = User.query.all()
    return render_template('admin/customers.html', customers=customers)


if __name__ == '__main__':
    # 创建数据库表
    with app.app_context():
        db.create_all()

        # 初始化存款类型
        if not Deposit.query.first():
            deposits = [
                Deposit(savingName='活期', descrip='无固定存期，可随时存取'),
                Deposit(savingName='定活两便', descrip='事先不约定存期，一次性存入，一次性支取'),
                Deposit(savingName='整存整取1年', descrip='1年定期存款'),
                Deposit(savingName='整存整取2年', descrip='2年定期存款'),
                Deposit(savingName='整存整取3年', descrip='3年定期存款')
            ]
            db.session.bulk_save_objects(deposits)

            # 创建管理员账户
            admin = User(
                customerName='admin',
                PID='110101199001011234',
                telephone='13800138000',
                password=generate_password_hash('admin123'),
                is_admin=True
            )
            db.session.add(admin)
            db.session.commit()

    app.run(debug=True)